package com.astrob.activitys;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.astrob.NavFrameSDK;
import com.astrob.NavFrameSDK.NavDest;
import com.astrob.NavFrameSDK.POIDescription;
import com.astrob.adapters.MidDestAdapter;
import com.astrob.adapters.MidDestAdapter.MidSwitchDestListener;
import com.astrob.adapters.PlanDestAdapter;
import com.astrob.adapters.PlanDestAdapter.DestItemListener;
import com.astrob.adapters.PlanHistoryAdapter;
import com.astrob.adapters.PlanHistoryAdapter.HistoryItemListener;
import com.astrob.model.FavoriteFileHandle;
import com.astrob.model.HistoryData;
import com.astrob.model.HistoryFileHandle;
import com.astrob.model.Msg;
import com.astrob.model.RoutePlanDataHandle;
import com.astrob.naviframe.Start;
import com.astrob.util.Utils;
import com.astrob.nhcmap.R;


import java.util.ArrayList;

public class RoutePlanActivity extends Activity {
	ListView mListviewDests;
	ListView mListHistory;
	RadioGroup mGroupRouteMethod;
	RadioButton mRadioCar;
	RadioButton mRadioWalk;
	PlanDestAdapter mDestAdapter;
	PlanHistoryAdapter mHistoryAdapter;
	DestItemListener mDestItemListener;
	ListView mListViewMidDest;
	MidDestAdapter mMidDestAdapter;
	boolean multiMode = false; //多目的地模式，指超过3个目的地模式
	ImageView mMidMode;
	boolean hasMid = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_routeplan);
		mListviewDests = (ListView) findViewById(R.id.listview_dests);
		mListviewDests.setVerticalScrollBarEnabled(false);
		FrameLayout destsController = (FrameLayout)findViewById(R.id.dests_controller);

		multiMode = true;
		if(multiMode){
			destsController.setVisibility(View.GONE);
			mListviewDests.setVisibility(View.VISIBLE);
		}
		mMidMode = (ImageView)findViewById(R.id.dests_mid_button);
		mListViewMidDest = (ListView)findViewById(R.id.listview_dests3);
		mListHistory = (ListView) findViewById(R.id.listview_history);
		mListHistory.setVerticalScrollBarEnabled(false);
		mGroupRouteMethod = (RadioGroup) findViewById(R.id.radioGroupRouteMethod);
		mRadioCar = (RadioButton) findViewById(R.id.radioCar);
		mRadioWalk = (RadioButton) findViewById(R.id.radioWalk);
		//默认设置行车模式
		onCarRoute(null);
		
		mDestItemListener = new DestItemListener() {

			@Override
			public void onSwitch() {
				if (RoutePlanDataHandle.getInstance().getDests().size() == 0) {
					alert("请先设置目的地");
					return;
				}
				HistoryData dest0 = RoutePlanDataHandle.getInstance()
						.getDests().get(0);
				HistoryData start = RoutePlanDataHandle.getInstance()
						.getStart();
				RoutePlanDataHandle.getInstance().getDests().set(0, start);
				RoutePlanDataHandle.getInstance().setStart(dest0);
				mDestAdapter.notifyDataSetChanged();
			}

			@Override
			public void onSoundInput() {

			}

			@Override
			public void onDel(int pos) {
				int count = RoutePlanDataHandle.getInstance().getDests().size();
				if (pos < 0 || pos >= count) {
					return;
				}
				RoutePlanDataHandle.getInstance().getDests().remove(pos);
				mDestAdapter.notifyDataSetChanged();
			}

			@Override
			public void onAdd() {
				AddRoutePointActivity.launch(RoutePlanActivity.this,
						AddRoutePointActivity.ADD_DEST);
			}

			@Override
			public void onChangeStart() {
				AddRoutePointActivity.launch(RoutePlanActivity.this,
						AddRoutePointActivity.SET_START);
			}

			@Override
			public void onChangeDest(int pos) {
				String preName = RoutePlanDataHandle.getInstance().getDests()
						.get(pos).name;
				AddRoutePointActivity.launchChangeDest(RoutePlanActivity.this,
						AddRoutePointActivity.SET_DEST, pos, preName);
			}
		};
		mDestAdapter = new PlanDestAdapter(this);
		mDestAdapter.setListener(mDestItemListener);
		mListviewDests.setAdapter(mDestAdapter);

		mHistoryAdapter = new PlanHistoryAdapter(this);
		mHistoryAdapter.setListener(new HistoryItemListener() {

			@Override
			public void onEmpty() {
				alertClearHistory();
			}

			@Override
			public void onDelFav(HistoryData data) {
				FavoriteFileHandle.getInstance().deleteByHist(data);
				mHistoryAdapter.notifyDataSetChanged();
			}

			@Override
			public void onAddFav(HistoryData data) {
				FavoriteFileHandle.getInstance().addByHist(data);
				mHistoryAdapter.notifyDataSetChanged();
			}

			@Override
			public void onItem(HistoryData data) {
				if (RoutePlanDataHandle.getInstance().getDests().size() >= PlanDestAdapter.MAX_DEST_COUNT) {
					alert("最多只能添加8个目的地！");
				} else {
					RoutePlanDataHandle.getInstance().getDests().add(data);
					updateList();
				}
			}
		});
		mListHistory.setAdapter(mHistoryAdapter);
		
		mMidDestAdapter = new MidDestAdapter(this);
		mMidDestAdapter.setListener(new MidSwitchDestListener() {
			@Override
			public void onSwitch() {
				if (RoutePlanDataHandle.getInstance().getDests().size() == 0) {
					alert("请先设置目的地");
					return;
				}
				HistoryData dest0 = RoutePlanDataHandle.getInstance()
						.getDests().get(0);
				HistoryData start = RoutePlanDataHandle.getInstance()
						.getStart();
				RoutePlanDataHandle.getInstance().getDests().set(0, start);
				RoutePlanDataHandle.getInstance().setStart(dest0);
				mMidDestAdapter.notifyDataSetChanged();
			}
		});
		mListViewMidDest.setAdapter(mMidDestAdapter);
		mListViewMidDest.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
				if(position == 0){
					AddRoutePointActivity.launch(RoutePlanActivity.this,
							AddRoutePointActivity.SET_START);
				}
				else if(position == 1){
					if(hasMid){
						AddRoutePointActivity.launchChangeDest(RoutePlanActivity.this,
								AddRoutePointActivity.SET_DEST, 0, "");
					}
					else {
						if(RoutePlanDataHandle.getInstance().getDests().size() == 0){
							AddRoutePointActivity.launch(RoutePlanActivity.this,
									AddRoutePointActivity.ADD_DEST);
						}
						else{
							AddRoutePointActivity.launchChangeDest(RoutePlanActivity.this,
									AddRoutePointActivity.SET_DEST, 0, "");
						}
					}
				} else { //position == 2
					if(RoutePlanDataHandle.getInstance().getDests().size() == 1){
						AddRoutePointActivity.launch(RoutePlanActivity.this,
								AddRoutePointActivity.ADD_DEST);
					}
					else{
						AddRoutePointActivity.launchChangeDest(RoutePlanActivity.this,
								AddRoutePointActivity.SET_DEST, 1, "");
					}
				}
			}
		});
	}
	public void onMidMode(View v){
		if (Utils.isFastDoubleClick())
			return;
		if(hasMid){
			hasMid = false;
			mMidDestAdapter.setHasMid(hasMid);
			//删除中间点
			RoutePlanDataHandle.getInstance().delDest(0);
			mMidMode.setBackgroundResource(R.drawable.route_point1);
			updateList();
		}
		else {
			hasMid = true;
			mMidDestAdapter.setHasMid(hasMid);
			RoutePlanDataHandle.getInstance().getDests().add(0, new HistoryData());
			mMidMode.setBackgroundResource(R.drawable.route_point2);
			updateList();
		}
	}
	protected void alertClearHistory() {
		if (HistoryFileHandle.getInstance().getNativeHistory().size() <= 0) {
			return;
		}
		new AlertDialog.Builder(this)
				.setTitle(getString(R.string.dlg_title))
				.setMessage("您确认清空所有历史记录吗？")
				.setPositiveButton(getString(R.string.yes),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// 确认清除数据
								HistoryFileHandle.getInstance()
										.clearNativeHistory();
								mHistoryAdapter.notifyDataSetChanged();
							}
						}).setNegativeButton(getString(R.string.cancel), null)
				.show();
	}

	protected void alert(String string) {
		Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
	}

	public static void launch(final Activity context, int requestCode) {
		Intent intent = new Intent(context, RoutePlanActivity.class);
		context.startActivityForResult(intent, requestCode);
	}

	public void updateList() {
		if(multiMode){
			mDestAdapter.notifyDataSetChanged();
		}
		else {
			mMidDestAdapter.notifyDataSetChanged();
		}
		mHistoryAdapter.notifyDataSetChanged();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Msg.ROUTE_LOAD) {
			updateList();
		} else if (resultCode == Msg.CHANGE_ROUTEMGR) {
			updateList();
		}
		if (requestCode == 3) {
			RoutePlanDataHandle.getInstance().setChangeStart(false);
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void onLoadRoute(View v) {
		if (Utils.isFastDoubleClick())
			return;

		Intent intent = new Intent(this, MyRoutePathActivity.class);
		startActivityForResult(intent, 0);
	}

	private boolean hasModified() {
		if (RoutePlanDataHandle.getInstance().getDests().size() > 0) {
			return true;
		}
		HistoryData start = RoutePlanDataHandle.getInstance().getStart();
		if (start.getName().compareTo("当前位置") != 0) {
			return true;
		}
		return false;
	}
	
	public void onCarRoute(View v) {
		Start.getInstance().MapKit().setCarRouteOption();
	}

	public void onWalkRoute(View v) {
		Start.getInstance().MapKit().setWalkRouteOption();
	}
	
	public void onBack(View v) {
		if (hasModified()) {
			new AlertDialog.Builder(this)
					.setTitle(getString(R.string.dlg_title))
					.setMessage("返回操作会清空您已设置的起点和目的地，确认要返回吗？")
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// 确认清除数据
									RoutePlanDataHandle.getInstance()
											.clearDests();
									RoutePlanDataHandle.getInstance()
											.clearStart();
									RoutePlanActivity.this
											.setResult(Msg.BACK_MAP_ID);
									RoutePlanActivity.this.finish();
								}
							})
					.setNegativeButton(getString(R.string.cancel), null).show();
			return;
		}
		setResult(Msg.BACK_MAP_ID);
		finish();
	}

	public void onFindPath(View v) {
		ArrayList<HistoryData> hisDests = RoutePlanDataHandle.getInstance()
				.getDests();

		int count = hisDests.size();
		if (count <= 0) {
			alert(getString(R.string.routemanagement_requires_at_least_one_destination));
			return;
		}

		HistoryData start = RoutePlanDataHandle.getInstance().getStart();

		if (start == null) {
			Start.getInstance().MapKit().clearNavStart();
			alert(getString(R.string.routemanagement_not_set_outset_start_navi_to_the_current_location));
		} else {
			Start.getInstance().MapKit().mNavStart.pos.lon = start.getLl().GetLon();
			Start.getInstance().MapKit().mNavStart.pos.lat = start.getLl().GetLat();
			Start.getInstance().MapKit().mNavStart.pname = 0;
			Start.getInstance().MapKit().mNavStart.name = start.getName();
		}

		Start.getInstance().MapKit().mNavDest = new NavDest[count];
		for (int i = 0; i < count; ++i) {
			Start.getInstance().MapKit().mNavDest[i] = toNavDest(hisDests.get(i));
			// save to history
			HistoryData data = hisDests.get(i);
			if (data.name == null || data.name.length() < 1
					|| 0 == data.name.compareTo("当前位置")) {
				Start.getInstance().MapKit().mTipPoiList = Start.getInstance()
						.MapKit().getNearPoi(data.getLl(), false);
				if (Start.getInstance().MapKit().mTipPoiList.size() > 0) {
					POIDescription poiData = Start.getInstance().MapKit().mTipPoiList
							.get(0);
					Start.getInstance().MapKit().mNavDest[i].name = poiData.name;
				} else {
					Start.getInstance().MapKit().mNavDest[i].name = (float) data.getLl()
							.GetLon() + " " + (float) data.getLl().GetLat();
				}
			}
		}

		RoutePlanDataHandle.getInstance().clearStart();
		RoutePlanDataHandle.getInstance().clearDests();
		setResult(Msg.NAVI_TO_DEST);
		finish();
	}

	private NavDest toNavDest(HistoryData data) {
		NavDest dest = NavFrameSDK.getInstance().new NavDest();
		dest.pos.lat = data.getLl().GetLat();
		dest.pos.lon = data.getLl().GetLon();
		dest.name = data.getName();
		dest.pname = 0;
		return dest;
	}

	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	public void onBackPressed() {
		onBack(null);
	}

}
